package com.mrli.controller;

import com.mrli.bean.RequestDto;
import com.mrli.openai.OpenAiService;
import com.mrli.openai.completion.chat.ChatCompletionChoice;
import com.mrli.openai.completion.chat.ChatCompletionRequest;
import com.mrli.openai.completion.chat.ChatCompletionResult;
import com.mrli.openai.completion.chat.ChatMessage;
import com.mrli.openai.config.ChatGptConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * description
 *
 * @author mrli
 * @version 1.0
 * @project chatgpt-web
 * @date: 2023/2/22 21:29
 * @copyright 2009–2022xxxxx all rights reserved.
 */
@RequestMapping("open")
@RestController
@Slf4j
public class OpenApiController {

    private  final ChatGptConfig config;

    public OpenApiController(ChatGptConfig config) {
        this.config=config;
    }

    /**
     * 测试openai
     *
     * @return
     */
    @PostMapping("test")
    public ResponseEntity<?> test(@RequestBody @Validated RequestDto requestDto) {
        OpenAiService service = new OpenAiService(config);
        String message = requestDto.getMessage();
            List<ChatMessage> messages = new ArrayList<>();
            ChatMessage e = new ChatMessage();
            e.setRole("user");
            e.setContent(message);
            messages.add(e);
            ChatCompletionRequest completionRequest = ChatCompletionRequest.builder()
                    .model("gpt-3.5-turbo")
                    .messages(messages)
                    .user("李大帅3")
                    .n(1)
                    .temperature(0d)
                    .topP(1D)
                    .build();
            ChatCompletionResult completion = service.createChatCompletion(completionRequest);
            List<ChatCompletionChoice> choices = completion.getChoices();
            choices.forEach(s -> log.info(s.getMessage().getContent()));

        return null;
    }
}
